package top.xchch.tool.resttemplate.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.xchch.tool.resttemplate.entity.Poetry;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发送get请求
 * @author sai.zhang
 * @date 2021-09-12 9:28
 */
@Slf4j
@RestController
public class GetRequestClient {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 请求参数在url上, 且有同名参数
     */
    @GetMapping("/get01")
    public List<Poetry> get01() {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "http://localhost:8080/findInIds?id={?}&id={?}&name={?}",
                String.class,10, 20, "hah");
        List<Poetry> poetries = JSON.parseObject(responseEntity.getBody(), new TypeReference<List<Poetry>>() {});
        // get01 - getForEntity 返回值: [{"id":666106231640,"title":"西塞山二首","author":"王周","content":"西塞名山立翠屏，浓岚横入半江青。\n千寻铁锁无由问，石壁空存道者形。\n匹妇顽然莫问因，匹夫何去望千春。\n翻思岵屺传诗什，举世曾无化石人。"}]
        log.info("get01 - getForEntity 返回值: {}", responseEntity.getBody());
        return poetries;
    }


    /**
     * 用map传参, 有同名参数
     */
    @GetMapping("/get02")
    public List<Poetry> get02() {
        Map<String, String> params = new HashMap<>();
        params.put("id01", "11");
        params.put("id02", "21");
        params.put("name", "haha");

        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8080/findInIds2?id={id01}&id={id02}&name={name}",
                String.class, params);
        List<Poetry> poetries = JSON.parseObject(responseEntity.getBody(), new TypeReference<List<Poetry>>() {});
        // get02 - getForEntity 返回值: [{"id":666106231640,"title":"西塞山二首","author":"王周","content":"西塞名山立翠屏，浓岚横入半江青。\n千寻铁锁无由问，石壁空存道者形。\n匹妇顽然莫问因，匹夫何去望千春。\n翻思岵屺传诗什，举世曾无化石人。"}]
        log.info("get02 - getForEntity 返回值: {}", responseEntity.getBody());
        return poetries;
    }

    /**
     * getForObject方法
     */
    @GetMapping("/get03")
    public List<Poetry> get03() {
        String responseStr = restTemplate.getForObject(
                "http://localhost:8080/findInIds3?id={?}&name={?}", String.class,10, "hah");
        // get03 - getForObject 返回值: [{"id":666106231640,"title":"西塞山二首","author":"王周","content":"西塞名山立翠屏，浓岚横入半江青。\n千寻铁锁无由问，石壁空存道者形。\n匹妇顽然莫问因，匹夫何去望千春。\n翻思岵屺传诗什，举世曾无化石人。"}]
        log.info("get03 - getForObject 返回值: {}", responseStr);
        List<Poetry> poetries = JSON.parseObject(responseStr, new TypeReference<List<Poetry>>() {});

        return poetries;
    }
}
